<template>
  <div class="warning-config-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>预警配置管理</h2>
      <p>管理水库预警规则配置，包括水位、流量、降雨等预警参数设置</p>
    </div>

    <!-- 统计概览 -->
    <el-row :gutter="20" class="stats-overview">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon color="#409eff" size="32"><Warning /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ totalRules }}</div>
              <div class="stats-label">预警规则总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon color="#67c23a" size="32"><CircleCheck /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ activeRules }}</div>
              <div class="stats-label">启用规则</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon color="#e6a23c" size="32"><Bell /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ todayAlerts }}</div>
              <div class="stats-label">今日预警</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon color="#f56c6c" size="32"><WarningFilled /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ highLevelAlerts }}</div>
              <div class="stats-label">高级别预警</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 查询表单 -->
    <el-card class="query-card" shadow="never">
      <el-form :model="queryForm" :inline="true" label-width="80px">
        <el-form-item label="规则名称">
          <el-input
            v-model="queryForm.ruleName"
            placeholder="请输入规则名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="预警类型">
          <el-select
            v-model="queryForm.warningType"
            placeholder="请选择预警类型"
            clearable
            style="width: 150px"
          >
            <el-option label="水位预警" value="water_level" />
            <el-option label="流量预警" value="flow" />
            <el-option label="降雨预警" value="rainfall" />
            <el-option label="库容预警" value="capacity" />
            <el-option label="综合预警" value="comprehensive" />
          </el-select>
        </el-form-item>
        <el-form-item label="预警级别">
          <el-select
            v-model="queryForm.warningLevel"
            placeholder="请选择预警级别"
            clearable
            style="width: 150px"
          >
            <el-option label="蓝色预警" value="blue" />
            <el-option label="黄色预警" value="yellow" />
            <el-option label="橙色预警" value="orange" />
            <el-option label="红色预警" value="red" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="queryForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="operation-card" shadow="never">
      <el-row justify="space-between">
        <el-col :span="12">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增规则
          </el-button>
          <el-button
            type="danger"
            :disabled="selectedRows.length === 0"
            @click="handleBatchDelete"
          >
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
          <el-button type="success" @click="handleExport">
            <el-icon><Download /></el-icon>
            导出配置
          </el-button>
          <el-button type="warning" @click="handleImport">
            <el-icon><Upload /></el-icon>
            导入配置
          </el-button>
        </el-col>
        <el-col :span="12" style="text-align: right">
          <el-button type="info" @click="handleTestRules">
            <el-icon><VideoPlay /></el-icon>
            规则测试
          </el-button>
          <el-button type="primary" @click="handleGlobalSettings">
            <el-icon><Setting /></el-icon>
            全局设置
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        :data="tableData"
        stripe
        border
        v-loading="tableLoading"
        @selection-change="handleSelectionChange"
        max-height="600"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="ruleName" label="规则名称" width="180" show-overflow-tooltip />
        <el-table-column prop="warningType" label="预警类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getWarningTypeTagType(row.warningType)">
              {{ getWarningTypeText(row.warningType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="warningLevel" label="预警级别" width="120">
          <template #default="{ row }">
            <el-tag :type="getWarningLevelTagType(row.warningLevel)">
              {{ getWarningLevelText(row.warningLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="threshold" label="阈值条件" width="200" show-overflow-tooltip />
        <el-table-column prop="notificationMethod" label="通知方式" width="150">
          <template #default="{ row }">
            <div class="notification-methods">
              <el-tag v-for="method in row.notificationMethod" :key="method" size="small" class="method-tag">
                {{ getNotificationMethodText(method) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              active-value="active"
              inactive-value="inactive"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="lastTriggered" label="最后触发时间" width="160" />
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column prop="creator" label="创建人" width="120" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" icon="View" @click="handleView(row)">查看</el-button>
            <el-button link type="warning" icon="Edit" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="success" icon="VideoPlay" @click="handleTest(row)">测试</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 预警规则表单弹窗 -->
    <WarningConfigFormDialog
      v-model:visible="formDialogVisible"
      :form-data="currentFormData"
      :dialog-type="dialogType"
      @confirm="handleFormConfirm"
    />

    <!-- 规则测试弹窗 -->
    <RuleTestDialog
      v-model:visible="testDialogVisible"
      :rule-data="currentTestRule"
    />

    <!-- 全局设置弹窗 -->
    <GlobalSettingsDialog
      v-model:visible="settingsDialogVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Plus,
  Delete,
  Download,
  Upload,
  VideoPlay,
  Setting,
  View,
  Edit,
  Warning,
  CircleCheck,
  Bell,
  WarningFilled
} from '@element-plus/icons-vue'
import WarningConfigFormDialog from './components/WarningConfigFormDialog.vue'
import RuleTestDialog from './components/RuleTestDialog.vue'
import GlobalSettingsDialog from './components/GlobalSettingsDialog.vue'

// 响应式数据
const tableLoading = ref(false)
const selectedRows = ref([])
const formDialogVisible = ref(false)
const testDialogVisible = ref(false)
const settingsDialogVisible = ref(false)
const dialogType = ref<'add' | 'edit' | 'view'>('add')
const currentFormData = ref({})
const currentTestRule = ref({})

// 统计数据
const totalRules = ref(28)
const activeRules = ref(24)
const todayAlerts = ref(5)
const highLevelAlerts = ref(2)

// 查询表单
const queryForm = reactive({
  ruleName: '',
  warningType: '',
  warningLevel: '',
  status: ''
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 模拟数据与过滤分页辅助
const allData = ref<any[]>([])
const randInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min
const randomChoice = <T>(arr: T[]) => arr[randInt(0, arr.length - 1)]
const pad2 = (n: number) => (n < 10 ? '0' + n : '' + n)
const formatDateTime = (d: Date) => `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`
const randomSubset = <T>(arr: T[]) => arr.filter(() => Math.random() < 0.5).length ? arr.filter(() => Math.random() < 0.5) : [randomChoice(arr)]

const generateMockData = () => {
  const count = randInt(10, 50)
  const types = ['water_level', 'flow', 'rainfall', 'capacity', 'comprehensive']
  const levels = ['blue', 'yellow', 'orange', 'red']
  const methods = ['sms', 'email', 'phone', 'app']
  const creators = ['张三', '李四', '王五', '赵六', '孙七', '周八']
  const typeTextMap: Record<string, string> = {
    water_level: '水位',
    flow: '流量',
    rainfall: '降雨',
    capacity: '库容',
    comprehensive: '综合'
  }
  const arr: any[] = []
  for (let i = 0; i < count; i++) {
    const type = randomChoice(types)
    const level = randomChoice(levels)
    const now = Date.now()
    const last = new Date(now - randInt(0, 15) * 24 * 3600 * 1000 - randInt(0, 23) * 3600 * 1000)
    const created = new Date(last.getTime() - randInt(1, 30) * 24 * 3600 * 1000)
    const threshold = (
      type === 'water_level' ? `水位 > ${randInt(180, 195)}.${randInt(0,9)}m` :
      type === 'flow' ? `流量 > ${randInt(800, 2000)}m³/s` :
      type === 'rainfall' ? `${randInt(6, 48)}小时降雨量 > ${randInt(50, 200)}mm` :
      type === 'capacity' ? `库容利用率 > ${randInt(70, 95)}%` :
      `综合风险指数 > ${(Math.random() * 0.5 + 0.5).toFixed(2)}`
    )
    arr.push({
      id: now + i,
      ruleName: `${typeTextMap[type]}预警规则-${i + 1}`,
      warningType: type,
      warningLevel: level,
      threshold,
      notificationMethod: randomSubset(methods),
      status: Math.random() < 0.75 ? 'active' : 'inactive',
      lastTriggered: formatDateTime(last),
      createTime: formatDateTime(created),
      creator: randomChoice(creators),
      description: `当${typeTextMap[type]}指标达到阈值时触发${level}级预警`
    })
  }
  return arr
}

const applyFiltersAndPaginate = () => {
  if (allData.value.length === 0) {
    allData.value = generateMockData()
  }
  const { ruleName, warningType, warningLevel, status } = queryForm
  let filtered = allData.value.slice()
  if (ruleName) {
    filtered = filtered.filter(item => String(item.ruleName).includes(ruleName))
  }
  if (warningType) {
    filtered = filtered.filter(item => item.warningType === warningType)
  }
  if (warningLevel) {
    filtered = filtered.filter(item => item.warningLevel === warningLevel)
  }
  if (status) {
    filtered = filtered.filter(item => item.status === status)
  }
  pagination.total = filtered.length
  const startIndex = (pagination.currentPage - 1) * pagination.pageSize
  const endIndex = startIndex + pagination.pageSize
  tableData.value = filtered.slice(startIndex, endIndex)
}

// 表格数据
const tableData = ref([
  {
    id: 1,
    ruleName: '水位超限预警',
    warningType: 'water_level',
    warningLevel: 'red',
    threshold: '水位 > 185.5m',
    notificationMethod: ['sms', 'email', 'phone'],
    status: 'active',
    lastTriggered: '2024-01-15 14:30:25',
    createTime: '2024-01-01 09:00:00',
    creator: '张三',
    description: '当水位超过185.5米时触发红色预警'
  },
  {
    id: 2,
    ruleName: '流量异常预警',
    warningType: 'flow',
    warningLevel: 'orange',
    threshold: '流量 > 1500m³/s',
    notificationMethod: ['sms', 'email'],
    status: 'active',
    lastTriggered: '2024-01-14 10:15:30',
    createTime: '2024-01-01 09:15:00',
    creator: '李四',
    description: '当流量超过1500立方米每秒时触发橙色预警'
  },
  {
    id: 3,
    ruleName: '降雨量预警',
    warningType: 'rainfall',
    warningLevel: 'yellow',
    threshold: '24小时降雨量 > 100mm',
    notificationMethod: ['sms'],
    status: 'active',
    lastTriggered: '2024-01-13 16:45:12',
    createTime: '2024-01-01 09:30:00',
    creator: '王五',
    description: '当24小时降雨量超过100毫米时触发黄色预警'
  },
  {
    id: 4,
    ruleName: '库容预警',
    warningType: 'capacity',
    warningLevel: 'blue',
    threshold: '库容利用率 > 85%',
    notificationMethod: ['email'],
    status: 'inactive',
    lastTriggered: '2024-01-10 08:20:45',
    createTime: '2024-01-01 09:45:00',
    creator: '赵六',
    description: '当库容利用率超过85%时触发蓝色预警'
  },
  {
    id: 5,
    ruleName: '综合风险预警',
    warningType: 'comprehensive',
    warningLevel: 'red',
    threshold: '综合风险指数 > 0.8',
    notificationMethod: ['sms', 'email', 'phone', 'app'],
    status: 'active',
    lastTriggered: '2024-01-12 12:30:15',
    createTime: '2024-01-01 10:00:00',
    creator: '孙七',
    description: '当综合风险指数超过0.8时触发红色预警'
  }
])

// 获取预警类型标签类型
const getWarningTypeTagType = (type: string) => {
  const typeMap = {
    water_level: 'primary',
    flow: 'success',
    rainfall: 'info',
    capacity: 'warning',
    comprehensive: 'danger'
  }
  return typeMap[type] || 'info'
}

// 获取预警类型文本
const getWarningTypeText = (type: string) => {
  const typeMap = {
    water_level: '水位预警',
    flow: '流量预警',
    rainfall: '降雨预警',
    capacity: '库容预警',
    comprehensive: '综合预警'
  }
  return typeMap[type] || type
}

// 获取预警级别标签类型
const getWarningLevelTagType = (level: string) => {
  const levelMap = {
    blue: 'info',
    yellow: 'warning',
    orange: '',
    red: 'danger'
  }
  return levelMap[level] || 'info'
}

// 获取预警级别文本
const getWarningLevelText = (level: string) => {
  const levelMap = {
    blue: '蓝色预警',
    yellow: '黄色预警',
    orange: '橙色预警',
    red: '红色预警'
  }
  return levelMap[level] || level
}

// 获取通知方式文本
const getNotificationMethodText = (method: string) => {
  const methodMap = {
    sms: '短信',
    email: '邮件',
    phone: '电话',
    app: 'APP推送'
  }
  return methodMap[method] || method
}

// 查询
const handleQuery = () => {
  tableLoading.value = true
  setTimeout(() => {
    applyFiltersAndPaginate()
    tableLoading.value = false
  }, 300)
}

// 分页大小变更
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  applyFiltersAndPaginate()
}

// 当前页变更
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  applyFiltersAndPaginate()
}

// API函数
const fetchWarningRules = async () => {
  applyFiltersAndPaginate()
}

const deleteWarningRule = async (id: number) => {
  const index = allData.value.findIndex(item => item.id === id)
  if (index > -1) {
    allData.value.splice(index, 1)
    applyFiltersAndPaginate()
    ElMessage.success('删除成功')
  }
}

const batchDeleteWarningRules = async (ids: number[]) => {
  allData.value = allData.value.filter(item => !ids.includes(item.id))
  applyFiltersAndPaginate()
  ElMessage.success(`成功删除 ${ids.length} 条记录`)
  selectedRows.value = []
}

const exportWarningConfig = async () => {
  // 模拟导出
  setTimeout(() => {
    ElMessage.success('导出成功')
  }, 1000)
}

const updateWarningRuleStatus = async (id: number, status: string) => {
  // 模拟API调用
  console.log(`更新规则 ${id} 状态为 ${status}`)
}

// 组件挂载
onMounted(() => {
  handleQuery()
})
</script>

<style scoped>
.warning-config-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.stats-overview {
  margin-bottom: 20px;
}

.stats-card {
  height: 100px;
}

.stats-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stats-icon {
  margin-right: 16px;
}

.stats-info {
  flex: 1;
}

.stats-value {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  line-height: 1;
  margin-bottom: 4px;
}

.stats-label {
  font-size: 14px;
  color: #666;
}

.query-card,
.operation-card,
.table-card {
  margin-bottom: 20px;
}

.notification-methods {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.method-tag {
  margin: 0;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 16px;
  margin-bottom: 16px;
}

:deep(.el-table .el-table__cell) {
  padding: 8px 0;
}
</style>